import { getUserInfoAPI, loginAPI, updatePasswordAPI } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/token";
import router from "@/router";

export default {
  namespaced: true,
  state: {
    token: getToken() || "",
    loginUser: {
      username: "",
    },
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token;
    },
    SET_USER_INFO(state, userInfo) {
      Object.assign(state.loginUser, userInfo);
    },
    REMOVE_TOKEN(state) {
      state.token = "";
    },
  },
  actions: {
    async login({ commit }, loginForm) {
      try {
        const token = await loginAPI(loginForm);
        // 存储token
        commit("SET_TOKEN", token);
        setToken(token);
      } catch (error) {
        return Promise.reject(error);
      }
    },
    async getLoginUserInfo({ commit }) {
      try {
        const userInfo = await getUserInfoAPI();
        commit("SET_USER_INFO", userInfo);
      } catch (error) {
        return Promise.reject(error);
      }
    },
    logout({ commit }) {
      commit("REMOVE_TOKEN");
      removeToken();
      router.push(`/login?redirect=${router.currentRoute.fullPath}`);
    },
    async updatePassword(store, updatePasswordForm) {
      try {
        await updatePasswordAPI(updatePasswordForm);
        store.dispatch("logout");
      } catch {
        return Promise.reject(new Error(""));
      }
    },
  },
  getters: {
    username: (state) => state.loginUser.username,
  },
};
